//
//  ChangeConnectViewController.swift
//  koolcar
//
//  Created by xiantian on 2023/9/26.
//

import UIKit
typealias ChangeConnectViewControllerBlock = (String) -> Void
class ChangeConnectViewController: UIViewController {
    var callBack: ChangeConnectViewControllerBlock?
    var bkgView: UIView!
    var contentView: UIView!
    var tableView: BaseTableView!
    var dataArray: [ServerModel] = []
    var selectIndex: NSInteger = 9999
    var bottomBtn: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        self.dataArray = ServerConfig.shared.getServerList()
        let curSiteUrl = ServerConfig.requestUrl()
        let curIndex = self.dataArray.firstIndex(where: {$0.siteUrl == curSiteUrl})
        if curIndex != nil {
            self.selectIndex = curIndex ?? 9999
        }
        
        bkgView = UIView()
        bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
        view.addSubview(bkgView)
        
        //内容
        contentView = UIView()
        contentView.backgroundColor = .white
        contentView.layer.cornerRadius = 8
        contentView.layer.masksToBounds = true
        bkgView.addSubview(contentView)
        
        tableView = BaseTableView.init(frame: CGRect.zero, style: .plain)
        tableView.register(ChangeConnectCell.self, forCellReuseIdentifier: "ChangeConnectCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.white
        tableView.separatorStyle = .none
        contentView.addSubview(tableView)
        
        bottomBtn = UIButton()
        bottomBtn.backgroundColor = Theme.mainColor
        bottomBtn.setup_titleLabel(text: "确定")
        bottomBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 16)
        bottomBtn.addTargetUsingBlock {[weak self] _ in
            self?.confirmBtnAction()
        }
        contentView.addSubview(bottomBtn)
        
        self.addSnpLayout()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.startAnimation()
    }
    
    private func addSnpLayout(){
        bkgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        contentView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(kScreenWidth - 40)
            make.height.lessThanOrEqualTo(kScreenHeight * 2/3)
            make.height.greaterThanOrEqualTo(500)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(0)
        }
        
        bottomBtn.snp.makeConstraints { make in
            make.top.equalTo(self.tableView.snp.bottom).offset(34)
            make.centerX.equalToSuperview()
            make.height.equalTo(40)
            make.width.equalTo(200)
            make.bottom.equalTo(-10)
        }
        self.view.layoutIfNeeded()
    }
    
    ///确定
    private func confirmBtnAction(){
        let model = self.dataArray[self.selectIndex]
        self.view.showLoadingHUDText()
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.baseParameter(param: ["":""]), objectType: BaseParameterModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! BaseParameterModel
            if resultObj.code == "1" && resultObj.data != nil {
                XTManageCenter.setLocalPlaceParameter(paramData: resultObj.data)
                XTManageCenter.setLocalDataString(aKey: UtilCenter.siteUrl , aValue: model.siteUrl ?? "")
                XTManageCenter.setLocalDataString(aKey: UtilCenter.h5Url , aValue: model.h5Url ?? "")
                self.callBack?(model.name ?? "") //回调loginView
                self.view.makeToast(message: MMLocalizedString("change_success", comment: "切换成功"))
                self.perform(#selector(self.handleSuccess), with: nil, afterDelay: 1.2)
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    @objc func handleSuccess(){
        self.closeAnimation()
    }
    
    private func startAnimation(){
        self.contentView.alpha = 0
        UIView.animate(withDuration: 0.4, delay: 0) {
            self.contentView.alpha = 1
            self.bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.6)
        }
    }
    
    private func closeAnimation(){
        self.bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.6)
        UIView.animate(withDuration: 0.2, delay: 0) {
            self.bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
            self.contentView.alpha = 0
        } completion: { flag in
            if flag {
                self.dismiss(animated: false)
            }
        }
    }
}


extension ChangeConnectViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ChangeConnectCell", for: indexPath) as! ChangeConnectCell
        
        if self.dataArray.count > indexPath.row {
            let model = self.dataArray[indexPath.row]
            cell.titleLab.text = model.name ?? ""
            cell.subTitleLab.text = model.siteUrl ?? ""
            
            if indexPath.row == selectIndex {
                cell.agreeImgView.isHidden = false
            }else{
                cell.agreeImgView.isHidden = true
            }
        }
        
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        self.selectIndex = indexPath.row
        self.tableView.reloadData()
    }
}


class ChangeConnectCell: UITableViewCell {
    var titleLab: UILabel = {
        let tempLab = UILabel()
        tempLab.textColor = Theme.titleLabColor
        tempLab.backgroundColor = UIColor.clear
        tempLab.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        tempLab.numberOfLines = 1
        tempLab.lineBreakMode = .byTruncatingTail
        tempLab.textAlignment = .left
        return tempLab
    }()
    
    var subTitleLab: UILabel = {
        let tempLab = UILabel()
        tempLab.textColor = Theme.lightNineColor
        tempLab.backgroundColor = UIColor.clear
        tempLab.font = UIFont.init(name: Theme.PingFangSCRegular, size: 12)
        tempLab.numberOfLines = 1
        tempLab.lineBreakMode = .byTruncatingTail
        tempLab.textAlignment = .left
        return tempLab
    }()
    
    var lineView: UIView = {
        let tempView = UIView()
        tempView.backgroundColor = Theme.lineColor
        return tempView
    }()
    
    var agreeImgView: UIImageView = {
        let tempImg = UIImageView()
        tempImg.isHidden = true
        tempImg.image = UIImage.init(named: "icon_agree")
        return tempImg
    }()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        contentView.addSubview(titleLab)
        contentView.addSubview(subTitleLab)
        contentView.addSubview(lineView)
        contentView.addSubview(agreeImgView)
        self.addSnpLayout()
    }
    
    private func addSnpLayout(){
        titleLab.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(12)
        }
        subTitleLab.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(titleLab.snp.bottom).offset(10)
            make.bottom.equalTo(-12)
        }
        lineView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.height.equalTo(1)
            make.bottom.equalTo(-1)
        }
        agreeImgView.snp.makeConstraints { make in
            make.right.equalTo(-12)
            make.centerY.equalToSuperview()
            make.width.equalTo(20)
            make.height.equalTo(20)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
